import { CSS_VARIABLE_MAP, PX_UNIT, changeCssVariable, changeTheme, changeColor } from '@/utils/theme-utils'
import Store from '@/store'

export class Theme {
  id = null
  name = null
  type = 'default'
  config = {
    headerBackgroundColor: '#ffffff',
    headerFontColor: '#606266',
    headerFontSize: '14',
    headerFontWeight: 'normal',
    headerHeight: '50',
    sideBackgroundColor: '#ffffff',
    sideInlineBackgroundColor: '#fafafa',
    sideFontColor: '#606266',
    sideMenuFontHoverColor: '#1890ff',
    sideMenuHoverBackgroundColor: 'transparent',
    sideMenuActiveBackgroundColor: '#e6f7ff',
    sideMenuFontActiveColor: '#1890ff',
    sidebarLineColor: '#1890ff',
    sideFontSize: '14',
    sideFontWeight: 'normal',
    sideWidth: '256',
    contentOutsideBackgroundColor: '#f0f2f5',
    contentInsideBackgroundColor: '#ffffff',
    contentFontColor: '#606266',
    primaryColor: '#1890ff'
  }

  constructor({ id, name, type, config }) {
    this.id = id
    this.name = name
    this.type = type || this.type
    this.config = Object.assign(this.config, config)
  }

  load() {
    changeTheme(this.type)
    changeColor(this.config.primaryColor, this.type)
    const keys = Object.keys(CSS_VARIABLE_MAP)
    keys.forEach(key => {
      const cssVariable = CSS_VARIABLE_MAP[key]
      const value = this.config[key]
      const cssVariableValue = PX_UNIT.includes(key) ? value + 'px' : value
      if (this.config[key]) {
        changeCssVariable(cssVariable, cssVariableValue, this.type)
      }
    })
  }

  save() {
    Store.dispatch('setTheme', this)
  }

  update(theme) {
    const keys = Object.keys(this.config)
    const diff = keys.some(key => this.config[key] !== theme[key])
    if (diff) {
      this.config = JSON.parse(JSON.stringify(theme.config))
      this.load()
      this.save()
    }
  }
}

export const defaultTheme = new Theme({
  id: -1,
  name: '默认'
})

export const darkTheme = new Theme({
  id: -2,
  name: '暗黑',
  type: 'dark',
  config: {
    headerBackgroundColor: '#141414',
    headerFontColor: '#ffffff',
    sideBackgroundColor: '#1f1f1f',
    sideInlineBackgroundColor: '#141414',
    sideFontColor: '#ffffffcc',
    sideMenuFontHoverColor: '#fff',
    sideMenuFontActiveColor: '#fff',
    sideMenuActiveBackgroundColor: '#177ddc',
    sidebarLineColor: '#177ddc',
    contentOutsideBackgroundColor: '#000000',
    contentInsideBackgroundColor: '#141414',
    contentFontColor: '#bfbfbf'
  }
})

export const combinationTheme = new Theme({
  id: -3,
  name: '黑白',
  type: 'default',
  config: {
    headerBackgroundColor: '#ffffff',
    headerFontColor: '#606266',
    sideBackgroundColor: '#1f1f1f',
    sideInlineBackgroundColor: '#141414',
    sideFontColor: '#ffffffcc',
    sideMenuFontHoverColor: '#fff',
    sideMenuFontActiveColor: '#fff',
    sideMenuActiveBackgroundColor: '#177ddc',
    sidebarLineColor: '#177ddc'
  }
})

export const themeList = [defaultTheme, darkTheme, combinationTheme]
